import * as types from './mutation-types';
import cookie from '../static/js/cookie';

// 类似于事件 每个mutation都有字符类型的事件类型和回调函数
//全局引入vue
import Vue from 'vue';
import Axios from 'axios';

Vue.prototype.$http = Axios
let startExpand = []; // 保存刷新后当前要展开的菜单项
function setExpand(source, url) {
    let sourceItem = '';
    for (let i = 0; i < source.length; i++) {
        sourceItem = JSON.stringify(source[i]); // 把菜单项转为字符串
        if (sourceItem.indexOf(url) > -1) { // 查找当前 URL 所对应的子菜单属于哪一个祖先菜单
            if (source[i].type === 'button') { // 导航菜单为按钮
                source[i].isSelected = true; // 设置选中高亮
                source[i].isExpanded = true; // 设置为展开
                startExpand.push(source[i]);
                // 递归下一级菜单，以此类推
                setExpand(source[i].sub_menu, url);
            }
            break;
        }
    }
}


export default {
    [types.SET_INFO](state) {
        state.userInfo = {
            name: cookie.getCookie('name'),
            groups: cookie.getCookie('groups'),
            token: cookie.getCookie('token')
        }
    },
    [types.MENUS_MODULE](state) {
        state.menusModule = {
            menus: [] || '',
            url: '/app/home/index' || ''
        }
    },
    [types.FIND_PARENTS](state, payload) {
        if (payload.menu.type === "button") {
            payload.menu.isExpanded = !payload.menu.isExpanded;
        } else if (payload.menu.type === "link") {
            if (startExpand.length > 0) {
                for (let i = 0; i < startExpand.length; i++) {
                    startExpand[i].isSelected = false;
                }
            }
            startExpand = []; // 清空展开菜单记录项
            setExpand(state.menusModule.menus, payload.menu.url);
        }
    },
    [types.FIRST_INIT](state, payload) {
        setExpand(state.menusModule.menus, payload.url);
    },


}
